package com.icss.train_sys_back.service.system_service.impl;

import com.icss.train_sys_back.entity.ResponseResult;
import com.icss.train_sys_back.entity.ResultEnum;
import com.icss.train_sys_back.entity.home.OrderEntity;
import com.icss.train_sys_back.entity.home.OrderPassengerEntity;
import com.icss.train_sys_back.entity.home.PassengerEntity;
import com.icss.train_sys_back.entity.system_manage.UserEntity;
import com.icss.train_sys_back.entity.ticket_manage.RefundTicketEntity;
import com.icss.train_sys_back.entity.ticket_manage.TicketEntity;
import com.icss.train_sys_back.entity.train_manage.StationEntity;
import com.icss.train_sys_back.entity.train_manage.TrainNumberEntity;
import com.icss.train_sys_back.mapper.home.OrderMapper;
import com.icss.train_sys_back.mapper.system_manage.UserMapper;
import com.icss.train_sys_back.mapper.ticket_manage.RefundTicketManageMapper;
import com.icss.train_sys_back.mapper.ticket_manage.TicketManageMapper;
import com.icss.train_sys_back.mapper.train_manage.StationMapper;
import com.icss.train_sys_back.mapper.train_manage.TrainNumberMapper;
import com.icss.train_sys_back.service.system_service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * @Author 小泽
 * @createTime 2025/9/16 14:18
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RefundTicketManageMapper refundTicketManageMapper;
    @Autowired
    private TicketManageMapper ticketManageMapper;
    @Autowired
    private TrainNumberMapper trainNumberMapper;
    @Autowired
    private StationMapper stationMapper;


    //用户登录
    @Override
    public UserEntity login(UserEntity user) {
        return userMapper.login(user);
    }

    //管理员查询所有用户
    @Override
    public List<UserEntity> getAllUser(String username, String name, Integer roleId, Integer status) {
        return userMapper.getAllUser(username, name, roleId, status);
    }

    //添加用户
    @Override
    public boolean addUser(UserEntity user) {
        return userMapper.addUser(user);
    }

    //修改用户
    @Override
    public boolean updateUser(UserEntity user) {
        return userMapper.updateUser(user);
    }

    //根据用户id删除某位用户  Integer  int
    @Override
    public boolean deleteUser(Integer userId) {
        return userMapper.deleteUser(userId);
    }

    //根据用户id修改状态
    @Override
    public boolean changeStatus(Integer userId, Integer status) {
        return userMapper.changeStatus(userId, status);
    }

    //检查用户名是否存在
    @Override
    public boolean checkUserName(String username) {
        return userMapper.checkUserName(username) != null;
    }

    //检查手机号是否存在
    @Override
    public boolean checkPhone(String phone) {
        return userMapper.checkPhone(phone) != null;
    }

    //检查邮箱号是否存在
    @Override
    public boolean checkEmail(String email) {
        return userMapper.checkEmail(email) != null;
    }

    //用户注册
    @Override
    public Integer register(UserEntity user) {
        return userMapper.register(user);
    }

    //更新人脸注册状态
    @Override
    public void updateFaceRegisterStatus(Integer userId) {
        userMapper.updateFaceRegisterStatus(userId);
    }

    //根据用户Id查询乘车人列表
    @Override
    public List<PassengerEntity> getPassengerListByUserId(Integer userId) {
        return userMapper.getPassengerListByUserId(userId);
    }

    //检查用户是否登录
    @Override
    public UserEntity checkLogin(Integer userId) {
        return userMapper.checkLogin(userId);
    }

    //根据车票Id  退票
    @Override
    @Transactional
    public ResponseResult refundTicketBiTicketId(String ticketId, String orderId, Integer userId) {
        //获取订单关联乘车人信息
        OrderPassengerEntity orderPassengerEntity = orderMapper.queryByUserId(userId, orderId);
        if (orderPassengerEntity == null) {
            log.warn("未找到用户订单信息，userId = {}", userId);
            return ResponseResult.fail(ResultEnum.FAIL);
        }

        //更新order表信息为 3--已退票
        orderMapper.updateOrderStatus(orderPassengerEntity.getOrderId(), 3);

        //更新座位 车票数量 + 1
        ticketManageMapper.incrTicketNumber(ticketId, 1);

        //根据车票Id 关联order_passenger表 找到对应的 seatId
        Integer seatId = orderMapper.findSeatIdByTicketId(ticketId, orderPassengerEntity.getPassengerId());

        //seat表将状态设置为0--空闲
        orderMapper.updateSeatStatusById(seatId, 0);

        //删除order_passenger信息
        //根据订单号和乘车人Id 删除记录   op表存储的场景是：一个用户给多个人买票 订单记录只有一条但是该订单下的乘车人有多个  一对多
        userMapper.deleteRecordByUserId(orderPassengerEntity.getPassengerId(), orderPassengerEntity.getOrderId());
        // ==========================================
        // 退票步骤完成后，向退票表插入退票记录
        // ==========================================
        try {
            //获取用户信息
            UserEntity userInfo = userMapper.getUserInfoByUserId(userId);
            if (userInfo == null) {
                log.warn("未找到用户信息，userId = {}", userId);
                return ResponseResult.fail(ResultEnum.FAIL);
            }

            //获取订单信息
            OrderEntity orderInfo = orderMapper.getOrderInfo(orderPassengerEntity.getOrderId());
            if (orderInfo == null || orderInfo.getTicket() == null) {
                log.warn("未找到订单信息或车票信息，orderId = {}", orderPassengerEntity.getOrderId());
                return ResponseResult.fail(ResultEnum.FAIL);
            }

            TicketEntity ticket = orderInfo.getTicket();

            //获取车次信息
            TrainNumberEntity trainNumber = trainNumberMapper.findTrainNumberByTrainId(ticket.getTrainNumberId());
            if (trainNumber == null) {
                log.warn("未找到车次信息，trainNumberId = {}", ticket.getTrainNumberId());
                return ResponseResult.fail(ResultEnum.FAIL);
            }

            //获取站点信息
            StationEntity startStation = stationMapper.getStationBySid(ticket.getStartStationId());
            StationEntity endStation = stationMapper.getStationBySid(ticket.getArrivalStationId());
            if (startStation == null || endStation == null) {
                log.warn("未找到站点信息，startStationId = {}, endStationId = {}", ticket.getStartStationId(), ticket.getArrivalStationId());
                return ResponseResult.fail(ResultEnum.FAIL);
            }

            //构造退票记录
            RefundTicketEntity refundTicketEntity = new RefundTicketEntity();
            refundTicketEntity.setRefundId("REF_" + UUID.randomUUID().toString().replace("-", "").substring(0, 18));
            refundTicketEntity.setOrderId(orderPassengerEntity.getOrderId());
            refundTicketEntity.setTicketId(ticketId);
            refundTicketEntity.setUserId(String.valueOf(userId));
            refundTicketEntity.setUsername(userInfo.getName() != null ? userInfo.getName() : userInfo.getUsername());
            refundTicketEntity.setTrainNumber(trainNumber.getTrainNumber());
            refundTicketEntity.setStartStation(startStation.getStationName());
            refundTicketEntity.setEndStation(endStation.getStationName());
            refundTicketEntity.setOriginalPrice(ticket.getTicketPrice());
            //退票金额等于票面价格（可根据实际业务规则调整）
            refundTicketEntity.setRefundAmount(ticket.getTicketPrice());
            refundTicketEntity.setApplyTime(LocalDateTime.now());
            //初始状态为待审核
            refundTicketEntity.setStatus(0);
            //退票原因（这里使用默认值，实际应该从前端传入）
            refundTicketEntity.setReason("用户主动申请退票");

            //插入退票记录
            refundTicketManageMapper.insertRefundTicket(refundTicketEntity);

            log.info("退票记录插入成功，refundId = {}", refundTicketEntity.getRefundId());

        } catch (Exception e) {
            log.error("插入退票记录失败", e);
            //这里可以选择抛出异常让事务回滚，或者记录错误并继续
            //根据业务需求决定，如果退票记录插入失败不影响主要退票流程，可以不抛出异常
        }

        return ResponseResult.success();
    }

    //根据userId  查对应的自己的passenger身份信息
    @Override
    public PassengerEntity getPassengerByUserId(Integer userId) {
        return userMapper.findPassengerInfoByUserId(userId);
    }

    //人脸信息更改时验证密码
    @Override
    public ResponseResult verifyPwd(Integer userId, String password) {
        UserEntity user = userMapper.verifyPwd(userId, password);
        return user != null ? ResponseResult.success() : ResponseResult.fail(ResultEnum.LOGIN_PWD_ERROR);
    }

    //历史订单查询
    @Override
    public List<OrderEntity> getHistoryOrderList(Integer userId, LocalDate startTime, LocalDate endTime, String orderId) {
        return userMapper.getHistoryOrderList(userId,startTime,endTime,orderId);
    }

}
